/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.b2b.modules.fm.web.base;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.b2b.common.service.BaseService;
import com.b2b.common.utils.SpringContextHolder;
import com.b2b.modules.fm.assets.FmConsts;
import com.b2b.modules.fm.assets.FmUtils;
import com.b2b.modules.fm.entity.base.FmStore;
import com.b2b.modules.fm.service.base.FmStoreService;
import com.b2b.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.b2b.common.utils.DateUtils;
import com.b2b.common.utils.MyBeanUtils;
import com.b2b.common.config.Global;
import com.b2b.common.persistence.Page;
import com.b2b.common.web.BaseController;
import com.b2b.common.utils.StringUtils;
import com.b2b.common.utils.excel.ExportExcel;
import com.b2b.common.utils.excel.ImportExcel;
import com.b2b.modules.fm.entity.base.FmEquipment;
import com.b2b.modules.fm.service.base.FmEquipmentService;

/**
 * 受控设备信息Controller
 * @author soldier lee
 * @version 2016-11-20
 */
@Controller
@RequestMapping(value = "${adminPath}/fm/base/fmEquipment")
public class FmEquipmentController extends BaseController {

	@Autowired
	private FmEquipmentService fmEquipmentService;
	
	@ModelAttribute
	public FmEquipment get(@RequestParam(required=false) String id) {
		FmEquipment entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = fmEquipmentService.get(id);
		}
		if (entity == null){
			entity = new FmEquipment();
		}
		return entity;
	}
	
	/**
	 * 设备信息列表页面
	 */
	@RequiresPermissions("fm:base:fmEquipment:list")
	@RequestMapping(value = {"list", ""})
	public String list(FmEquipment fmEquipment, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<FmEquipment> page = fmEquipmentService.findPage(new Page<FmEquipment>(request, response), fmEquipment); 
		model.addAttribute("page", page);
		return "modules/fm/base/fmEquipmentList";
	}

	/**
	 * 查看，增加，编辑设备信息表单页面
	 */
	@RequiresPermissions(value={"fm:base:fmEquipment:view","fm:base:fmEquipment:add","fm:base:fmEquipment:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(FmEquipment fmEquipment, Model model) {
		if(StringUtils.isEmpty(fmEquipment.getId())){
			fmEquipment.setEqu000(Global.SHOW);
			fmEquipment.setEqu015(FmConsts.FmStore.RECORD_NEW.getIndex().toString());
			fmEquipment.setEqu017(FmConsts.FmStoreStatus.on.toString());
		}
		//处理从门店直接链接进行新增设备数据的情况
		String storeno = fmEquipment.getEqu013();
		if (StringUtils.isNotEmpty(storeno)){
			FmStore fmStore = FmUtils.getFmStore(storeno);
			if (StringUtils.isNotEmpty(fmStore)){
				fmEquipment.setFmStore(fmStore);
				//同步 主机号 属性
				fmEquipment.setEqu016(fmStore.getSto005());
			}
		}
		model.addAttribute("fmEquipment", fmEquipment);
		return "modules/fm/base/fmEquipmentForm";
	}

	/**
	 * 保存设备信息
	 */
	@RequiresPermissions(value={"fm:base:fmEquipment:add","fm:base:fmEquipment:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(FmEquipment fmEquipment, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, fmEquipment)){
			return form(fmEquipment, model);
		}
		if(!fmEquipment.getIsNewRecord()){//编辑表单保存
			FmEquipment t = fmEquipmentService.get(fmEquipment.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(fmEquipment, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			fmEquipmentService.save(t);//保存
		}else{//新增表单保存
			fmEquipmentService.save(fmEquipment);//保存
		}
		model.addAttribute("errCode",200).addAttribute("message", "保存设备信息成功");
		return "modules/fm/base/fmEquipmentForm";
	}
	
	/**
	 * 删除设备信息
	 */
	@RequiresPermissions("fm:base:fmEquipment:del")
	@RequestMapping(value = "delete")
	public String delete(FmEquipment fmEquipment, RedirectAttributes redirectAttributes) {
		fmEquipmentService.delete(fmEquipment);
		addMessage(redirectAttributes, "删除设备信息成功");
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmEquipment/?repage";
	}
	
	/**
	 * 批量删除设备信息
	 */
	@RequiresPermissions("fm:base:fmEquipment:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			fmEquipmentService.delete(fmEquipmentService.get(id));
		}
		addMessage(redirectAttributes, "删除设备信息成功");
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmEquipment/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("fm:base:fmEquipment:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(FmEquipment fmEquipment, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "设备信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<FmEquipment> page = fmEquipmentService.findPage(new Page<FmEquipment>(request, response, -1), fmEquipment);
    		new ExportExcel("设备信息", FmEquipment.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出设备信息记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmEquipment/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fm:base:fmEquipment:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<FmEquipment> list = ei.getDataList(FmEquipment.class);
			for (FmEquipment fmEquipment : list){
				try{
					fmEquipmentService.save(fmEquipment);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条设备信息记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条设备信息记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入设备信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmEquipment/?repage";
    }
	
	/**
	 * 下载导入设备信息数据模板
	 */
	@RequiresPermissions("fm:base:fmEquipment:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "设备信息数据导入模板.xlsx";
    		List<FmEquipment> list = Lists.newArrayList(); 
    		new ExportExcel("设备信息数据", FmEquipment.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmEquipment/?repage";
    }

	/**
	 * 根据门店获取设备信息列表页面  瀑布流加载
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "byStore")
	public String byStore(FmEquipment fmEquipment, HttpServletRequest request, HttpServletResponse response, Model model) {
		fmEquipment.setEqu000(Global.SHOW);
		fmEquipment.getSqlMap().put("dsf", BaseService.dataScopeFilter(UserUtils.getUser(), "o", "u"));
		List<FmEquipment> list = fmEquipmentService.findList(fmEquipment);
		FmStoreService fmStoreService = SpringContextHolder.getBean(FmStoreService.class);
		FmStore fmStore = fmStoreService.findUniqueByProperty("sto002",fmEquipment.getEqu013());
		model.addAttribute("list", list).addAttribute("fmEquipment",fmEquipment).addAttribute("fmStore",fmStore);
		return "modules/fm/base/fmEquipmentByStore";
	}

	/**
	 * 验证设备编号 在门店唯一
	 * @param equ001
	 * @param equ013
	 * @param response
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "validateDno")
	public boolean validateDno(String equ001,String equ013, HttpServletResponse response, Model model) {
		FmEquipment fmEquipment = new FmEquipment();
		fmEquipment.setEqu001(equ001);
		fmEquipment.setEqu013(equ013);

		List list = fmEquipmentService.findList(fmEquipment);
		if(list != null&& list.size()>0){
			return true;
		}else{
			return false;
		}
	}

}